package com.lgk.controller;

import com.github.pagehelper.PageInfo;
import com.lgk.domain.Role;
import com.lgk.domain.UR;
import com.lgk.domain.User;
import com.lgk.service.RoleService;
import com.lgk.service.URService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class URController {

    @Autowired
    private URService urService;

    @Autowired
    private RoleService roleService;

    /**
     * go to 角色界面
     * @param model
     * @param username
     * @return
     */
    @RequestMapping("/to/userRoleList/{username}")
    public String toUserRole(Model model, @PathVariable("username")String username){
        return getString(model, username,1, "");
    }

    /**
     * 封装一个公共数据和跳转用户页
     * @param model
     * @param username
     * @return
     */
    private String getString(Model model, @PathVariable("username") String username,Integer pageNum, String userName) {
        PageInfo<User> page;
        page = urService.getPageUserRole(pageNum, userName);
        model.addAttribute("page", page);
        for (User u: page.getList()) {
            System.out.println(u);
        }
        //登陆者姓名
        model.addAttribute("username", username);
        //用户名查询
        model.addAttribute("searchName",userName);

        return "user_role_list";
    }

    /**
     * 分页查询用户全部角色
     * @param model
     * @param pageNum
     * @param username
     * @return
     */
    @RequestMapping(value = "/getUserRolePage/{username}/{pageNum}", method = RequestMethod.GET)
    public String getUserRolePage(Model model,@PathVariable("pageNum") Integer pageNum, @PathVariable("username") String username,
                                  User user) {

        return getString(model, username, pageNum,user.getName());
    }

    /**
     * 根据id查询用户
     * @param id
     */
    @RequestMapping(value = "/getUserRole/{id}/{username}",method = RequestMethod.GET)
    public String getById(User user, @PathVariable("username")String username, @PathVariable("id")Integer id, Model model) {
        User changeUser = urService.getById(id);
        List<Role> roleList = roleService.geRoleAll();
        model.addAttribute("RoleList", roleList);
        model.addAttribute("changeUser", changeUser);
        model.addAttribute("username", username);
        //用户名查询
        model.addAttribute("searchName",user.getName());
        return "user_role_update";
    }

}
